import { createStore, Store, useStore as useVuexStore } from 'vuex'
import { IRootState, IStoreType } from './types'
import login from '@/store/login/login'
import system from '@/store/main/system/system'
import dashboard from '@/store/main/analysis/dashboard'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<IRootState>({
  state() {
    return {
      name: 'coderLj',
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  mutations: {
    changeDepartmentList(state, list) {
      state.entireDepartment = list
    },
    changeRoleList(state, list) {
      state.entireRole = list
    },
    changeMenuList(state, list) {
      state.entireMenu = list
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // const departmentResult = await getPageListData('/department/list', {
      //   offset: 0,
      //   size: 100
      // })
      // const { list: departmentList } = departmentResult.data
      // commit('changeDepartmentList', departmentList)

      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 100
      })
      const { list: roleList } = roleResult.data
      commit('changeRoleList', roleList)

      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data
      commit('changeMenuList', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})

//用于将localStorage中的token等数据初始化进vuex
//因为vuex中的数据在页面刷新时会消失，vuex的数据默认保存在内存中
export function setupStore() {
  store.dispatch('login/loadLocalLogin')
}

export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
